package com.lyhengtongwl.zqsnews.ui.activity;

import android.Manifest;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.adapter.PosterAdapter;
import com.lyhengtongwl.zqsnews.base.BaseActivity;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.utils.NewsOpenShare;
import com.lyhengtongwl.zqsnews.utils.NewsShareUtils;
import com.lyhengtongwl.zqsnews.utils.NewsToastUtils;
import com.lyhengtongwl.zqsnews.utils.OpenSdkUtils;
import com.lyhengtongwl.zqsnews.utils.PermissionUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.SaveHttpImgUtils;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.utils.TitleBuilder;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

public class QCInvitationActivity extends BaseActivity {
    @BindView(R.id.vp_loop)
    ViewPager vp;
    @BindView(R.id.iv_title_right)
    ImageView iv_title_right;
    @BindView(R.id.ll_0)
    LinearLayout ll_0;
    @BindView(R.id.ll_1)
    LinearLayout ll_1;
    @BindView(R.id.ll_2)
    LinearLayout ll_2;

    @BindView(R.id.iv_0)
    ImageView iv_0;
    @BindView(R.id.iv_1)
    ImageView iv_1;
    @BindView(R.id.iv_2)
    ImageView iv_2;
    private String type = "0";
    private int margin;
    private List<String> list;
    private final String[] PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,//存储权限
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //回调结果
        PermissionUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 获取相关权限
     */
    private void getPermission() {
//        if (!PermissionUtils.getInstance().checkPermission(QCInvitationActivity.this,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//            PermissionUtils.getInstance().checkPermissions(this, PERMISSIONS, permissionsResult);
//        } else {
        switch (type) {
            case "0":
                if (list.size() > 0)
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
//                            new NewsOpenShare(QCInvitationActivity.this).shareImgToWXF(OpenSdkUtils.returnBitMap(QCInvitationActivity.this, list.get(vp.getCurrentItem())));
                            NewsShareUtils.shareImgToFriends(QCInvitationActivity.this, SaveHttpImgUtils.returnBitMap(QCInvitationActivity.this, list.get(vp.getCurrentItem())));
                        }
                    }).start();
                break;
            case "1":
                if (list.size() > 0)
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
//                            new NewsOpenShare(QCInvitationActivity.this).shareImgToWXFC(OpenSdkUtils.returnBitMap(QCInvitationActivity.this, list.get(vp.getCurrentItem())));
                            NewsShareUtils.shareImgToCircleFriends(QCInvitationActivity.this, SaveHttpImgUtils.returnBitMap(QCInvitationActivity.this, list.get(vp.getCurrentItem())));
                        }
                    }).start();
                break;
//            }
        }
    }

    //创建监听权限的接口对象
    PermissionUtils.IPermissionsResult permissionsResult = new PermissionUtils.IPermissionsResult() {
        @Override
        public void passPermissons() {
            //当提示申请权限时，全部通过，会走这里（6.0以下直接走这里）
            switch (type) {
                case "0":
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            new NewsOpenShare(QCInvitationActivity.this).shareImgToWXF(OpenSdkUtils.returnBitMap(QCInvitationActivity.this, list.get(vp.getCurrentItem())));
//                        NewsShareUtils.shareImgToFriends(QCInvitationActivity.this, SaveHttpImgUtils.returnBitMap(QCInvitationActivity.this, list.get(vp.getCurrentItem())));
                        }
                    }).start();
                    break;
                case "1":
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            new NewsOpenShare(QCInvitationActivity.this).shareImgToWXFC(OpenSdkUtils.returnBitMap(QCInvitationActivity.this, list.get(vp.getCurrentItem())));
//                        NewsShareUtils.shareImgToCircleFriends(QCInvitationActivity.this, SaveHttpImgUtils.returnBitMap(QCInvitationActivity.this, list.get(vp.getCurrentItem())));
                        }
                    }).start();
                    break;
            }
        }

        @Override
        public void forbitPermissons() {
            NewsToastUtils.showToast(App.getContext(), "权限已被拒绝，请手动在设置里打开存储权限！");
        }
    };

    @Override
    public void setListen() {

    }

    @OnClick({R.id.ll_shareToFriends, R.id.ll_shareToFriendsC, R.id.iv_0, R.id.iv_1, R.id.iv_2, R.id.tv_share})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ll_shareToFriends://朋友分享
                type = "0";
                getPermission();
//                if (PermissionUtils.getInstance().checkPermission(QCInvitationActivity.this,
//                        Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                } else {
//                    PermissionUtils.getInstance().showSystemPermissionsSettingDialog(QCInvitationActivity.this);
//                }
                break;
            case R.id.ll_shareToFriendsC://朋友圈分享
                type = "1";
                getPermission();
//                if (PermissionUtils.getInstance().checkPermission(QCInvitationActivity.this,
//                        Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            new NewsOpenShare(QCInvitationActivity.this).shareImgToWXFC(OpenSdkUtils.returnBitMap(QCInvitationActivity.this, list.get(vp.getCurrentItem())));
////                        NewsShareUtils.shareImgToCircleFriends(QCInvitationActivity.this, SaveHttpImgUtils.returnBitMap(QCInvitationActivity.this, list.get(vp.getCurrentItem())));
//                        }
//                    }).start();
//                } else {
//                    PermissionUtils.getInstance().showSystemPermissionsSettingDialog(QCInvitationActivity.this);
//                }
                break;
            case R.id.iv_0:
                vp.setCurrentItem(0, true);
                setSupernatant(0);
                break;
            case R.id.iv_1:
                vp.setCurrentItem(1, true);
                setSupernatant(1);
                break;
            case R.id.iv_2:
                vp.setCurrentItem(2, true);
                setSupernatant(2);
                break;
            case R.id.tv_share:
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        new NewsOpenShare(QCInvitationActivity.this).shareImgToWX(OpenSdkUtils.returnBitMap(QCInvitationActivity.this, list.get(vp.getCurrentItem())));
////                        NewsShareUtils.shareImgToCircleFriends(QCInvitationActivity.this, SaveHttpImgUtils.returnBitMap(QCInvitationActivity.this, list.get(vp.getCurrentItem())));
//                    }
//                }).start();
                break;

        }
    }

    @Override
    protected boolean isStatusBarBlack() {
        return true;
    }


    @Override
    public void setTitleBarColor() {
        iv_title_right.setVisibility(View.GONE);
        new TitleBuilder(this).setTitleText("二维码收徒")
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_qc_share;
    }

    //静态内部类handler，防止内存泄漏
    //获取三张海报
    private void getHB() {
        Task.getApiService().getShareOr().enqueue(new MyCallback<NewsBaseEntity>(QCInvitationActivity.this) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                try {
                    assert response.body() != null;
                    list = new ArrayList<>();
                    if ("1".equals(response.body().getCode())) {
                        String jsonStr = JSONObject.toJSONString(response.body().getData());
                        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                        String shareCode = jsonObject.getString("shareCode");
                        SPUtils.put(App.getContext(), "shareCode", shareCode);
                        JSONArray jsonArray = jsonObject.getJSONArray("shareImgs");

                        if (jsonArray.size() > 0) {
                            for (int i = 0; i < jsonArray.size(); i++) {
                                list.add(jsonArray.get(i).toString());
                            }
                            Picasso.with(App.getContext()).load(list.get(0)).into(iv_0);
                            Picasso.with(App.getContext()).load(list.get(1)).into(iv_1);
                            Picasso.with(App.getContext()).load(list.get(2)).into(iv_2);
                            vp.setPageMargin(-margin);
                            vp.setOffscreenPageLimit(3);//预加载3个页面
                            vp.setPageTransformer(false, new LoopTransformer());
                            vp.setAdapter(new PosterAdapter(QCInvitationActivity.this, list));
                            vp.setCurrentItem(1, true);
                            ll_0.setVisibility(View.GONE);
                            ll_1.setVisibility(View.VISIBLE);
                            ll_2.setVisibility(View.GONE);
                            vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                @Override
                                public void onPageScrolled(int i, float v, int i1) {

                                }

                                @Override
                                public void onPageSelected(int i) {
                                    setSupernatant(i);
                                }

                                @Override
                                public void onPageScrollStateChanged(int i) {

                                }
                            });
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    @Override
    public void initView() {
        margin = ScreenUtil.dip2px(App.getContext(), 40);
        getHB();
    }

    //设置显示
    private void setSupernatant(int CurrentItem) {
        switch (CurrentItem) {
            case 0:
                ll_0.setVisibility(View.VISIBLE);
                ll_1.setVisibility(View.GONE);
                ll_2.setVisibility(View.GONE);
                break;
            case 1:
                ll_0.setVisibility(View.GONE);
                ll_1.setVisibility(View.VISIBLE);
                ll_2.setVisibility(View.GONE);
                break;
            case 2:
                ll_0.setVisibility(View.GONE);
                ll_1.setVisibility(View.GONE);
                ll_2.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void initData() {
    }


}
